/**
 * 鼠标移动生成跟随元素
 */

const createHeart = event => {
    const span = document.createElement("span");

    const size = Math.random() * 50 + 20;

    span.style.left = event.clientX - size / 2 + "px";
    span.style.top = event.clientY - size / 2 + "px";

    span.style.width = size + "px";
    span.style.height = size + "px";

    const rotateValue = Math.random() * 360;
    span.style.transform = "rotate(" + rotateValue + "deg)";

    document.body.append(span);

    setTimeout(function () {
        span.remove();
    }, 1000);
};

document.addEventListener("mousemove", function (event) {
    createHeart(event);
});

document.addEventListener("touchmove", function (event) {
    createHeart(event);
});

document.addEventListener("click", function (event) {
    createHeart(event);
});


/**
 * 跟随 svg 路径动画中移动元素的实时位置，生成跟随元素
 */

const heartMover = document.querySelector("#heart");

const moveHeart = heartMover => {
    setInterval(() => {
        // 获取元素的位置和尺寸
        const { top, left, width, height } = heartMover.getBoundingClientRect();

        // 计算元素中心点的坐标
        const x = left + width / 2;
        const y = top + height / 2;

        const span = document.createElement("span");

        const size = Math.random() * 50 + 20;

        span.style.left = x + "px";
        span.style.top = y + "px";

        span.style.width = size + "px";
        span.style.height = size + "px";

        const rotateValue = Math.random() * 360;
        span.style.transform = "rotate(" + rotateValue + "deg)";

        document.body.append(span);

        setTimeout(function () {
            span.remove();
        }, 1000);
    }, 50);
};

/**
 * svg 描边动画
 */

const heartPath = document.querySelector("#heartPath");
// js 获取 svg 路径的总长度（css 设置 100% 是不准的）
const stickLength = heartPath.getTotalLength();
heartPath.style.strokeDasharray = stickLength + "px";
heartPath.style.strokeDashoffset = stickLength + "px";

/**
 * js 控制 svg 动画的开始
 */
function startAnimation() {
    const anim = document.getElementById("motionAnimation");
    // 触发开始 svg 路径动画的事件
    anim.beginElement();
    // 生成跟随元素
    moveHeart(heartMover);

    // 控制 svg 描边动画的开始
    heartPath.style.animation = "line1Move 10s linear infinite ";
}



window.onload = function () {
    // 页面加载完，自动开始 svg 动画。（也可以绑定到按钮，点击开始动画）
    startAnimation();
};


